#include"mystdio.h"

const char* To_string(int flush_mode)
{
    if(flush_mode & None_Flush) 
            return "Nono Flush";
        else if(flush_mode & Line_Flush)
            return "Line_Flush";
        else if(flush_mode & Full_Flush)
            return "Full_Flush";
    }

   void print_buff(myfile* fp)
   {
       printf("fd: %d\n", fp->fileno);
       printf("fd: %d\n", fp->pos);
       printf("buff: %s\n", fp->buff);
       printf("flush_mode: %s\n", To_string(fp->flush_mode));
   }

    myfile* my_fopen(const char* path, const char* mode)
    {
        int flag = -1;
        if(strcmp(mode, "r") == 0)
            flag = O_RDONLY;
        else if(strcmp(mode, "w") == 0)
            flag = O_WRONLY|O_CREAT|O_TRUNC;
        else if(strcmp(mode, "a") == 0)
            flag = O_WRONLY|O_CREAT|O_APPEND;
        else 
            return NULL;


        int fd = -1;
        if(flag & O_RDONLY)
            fd = open(path, flag); 
        else 
        {
            umask(0);
            fd = open(path, flag, 0666);
        }
        if(fd < 0)
            return NULL;


        myfile*  fp = (myfile*)malloc(sizeof(myfile));
        if(fp == NULL)
            return NULL;

        fp->fileno = fd;
        fp->pos = 0;
        fp->cap = SIZE;
        fp->flush_mode = Line_Flush;
        return fp;
    }
    
    void my_fflush(myfile* fp)
    {
        if(fp->pos == 0) 
            return ;
        write(fp->fileno, fp->buff, fp->pos);
        fp->pos = 0;
    }

    void my_fclose(myfile* fp)
    {
        my_fflush(fp);
        close(fp->fileno);
        free(fp);
    }

    int my_fwrite(myfile* fp, const char* str, int size)
    {
        memcpy(fp->buff + fp->pos, str, size);
        fp->pos += size;

        if(fp->flush_mode == Line_Flush && fp->buff[fp->pos - 1] == '\n')
            my_fflush(fp);
        else if(fp->flush_mode == Full_Flush && fp->pos == fp->cap)
            my_fflush(fp);

        return 0;
    }

